package vip.specimen.system.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.specimen.system.datasource.entity.SystemAliPayEntity;
import vip.specimen.system.repository.SystemAliPayConfigRepository;
import vip.specimen.system.datasource.validation.SystemAliPayConfigValidation;
import vip.specimen.system.common.implement.AliPay;

import javax.annotation.Resource;
import java.util.Calendar;

/**
 * *@Author: 余浪人
 * *@Date：2021/3/25 12:40
 * *@Email:yulangren520@Gmail.com
 * *@QQ:1368419640
 **/
@Service
public class SystemAliPayConfigService {
    @Resource
    private SystemAliPayConfigRepository aliPayConfigRepository;
    @Resource
    private AliPay aliPay;

    @Transactional
    SystemAliPayEntity initialize() {
        return this.aliPayConfigRepository.save(new SystemAliPayEntity("https://openapi.alipay.com/gateway.do", "", "", "", "", ""));
    }

    /**
     * 获取配置信息
     *
     * @return 配置
     */
    public SystemAliPayEntity getConfig() {
        return this.aliPayConfigRepository.count() == 0 ? this.initialize() : this.aliPayConfigRepository.findFirstByOrderByCreateTimeDesc();
    }

    /**
     * 更新配置
     *
     * @param aliPayConfigValidation 验证对象
     * @return 配置
     */
    public SystemAliPayEntity update(SystemAliPayConfigValidation aliPayConfigValidation) {
        SystemAliPayEntity aliPayEntity = this.getConfig();
        aliPayEntity.setAliPayPublicKey(aliPayConfigValidation.getAliPayPublicKey());
        aliPayEntity.setAppId(aliPayConfigValidation.getAppId());
        aliPayEntity.setAppPrivateKey(aliPayConfigValidation.getAppPrivateKey());
        aliPayEntity.setContentEncryption(aliPayConfigValidation.getContentEncryption());
        aliPayEntity.setServerURL(aliPayConfigValidation.getServerURL());
        aliPayEntity.setAppPublicKey(aliPayConfigValidation.getAppPublicKey());
        aliPayEntity.setUpdateTime(Calendar.getInstance().getTime());
        return this.aliPayConfigRepository.save(aliPayEntity);
    }
}
